<template>
  <div v-loading="loading" class="tab-container">
    <!-- 空间添加成员 -->
    <el-card v-if="enableShowCard" class="box-card wl-card">
      <div slot="header" class="clearfix">
        <span>添加成员</span>
      </div>
      <el-form ref="mbform" :model="mbform" :rules="mbformRules" label-width="90px">
        <el-form-item label="成员名称" prop="userId">
          <el-select v-model="mbform.userId" placeholder="搜索添加用户" filterable class="wl-input" @focus="handleFocusUsers()" @keyup.native="handleInputUserName">
            <el-option v-for="item in userList" :key="item.user_id" :label="item.username" :value="item.user_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="成员角色" prop="role">
          <el-select v-model="mbform.role" placeholder="请分配角色" class="wl-input">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" icon="el-icon-plus" class="wl-append" @click="handleAddSpaceMember()">添加</el-button>
    </el-card>

    <!-- 查询与新增 -->
    <el-form ref="form" :model="form">
      <el-form-item>
        <el-input v-model="form.queryName" placeholder="请输入内容" class="wl-input" @input="handleQuery()">
          <el-button slot="append" icon="el-icon-search" class="wl-search" @click="handleQuery()" />
        </el-input>
        <el-button v-if="enableCreate" type="primary" icon="el-icon-edit" class="wl-append" @click="handleAdd()">新建</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table :data="memberList" :header-cell-style="{background:'#f4f4f5'}" class="wl-table">
      <el-table-column prop="username" :show-overflow-tooltip="true" label="用户名" width="200">
        <template slot-scope="scope">
          <div class="wl-avatar">
            <span><img :src="'/static/assets' + scope.row.avatar" alt="" /></span>
            <span style="margin-left: 10px">{{ scope.row.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="email" :show-overflow-tooltip="true" label="邮箱" width="200" />
      <el-table-column prop="role" :show-overflow-tooltip="true" label="角色" width="100">
        <template slot-scope="scope"><span>{{getRoleDesc(scope.row.role)}}</span></template>
      </el-table-column>
      <el-table-column prop="status" :show-overflow-tooltip="true" label="状态" width="100" />
      <el-table-column prop="created_at" :show-overflow-tooltip="true" label="创建时间" width="140" />
      <el-table-column prop="updated_at" :show-overflow-tooltip="true" label="更新时间" width="140" />
      <el-table-column prop="operate" label="操作" min-width="120" >
        <template slot-scope="scope">
          <el-button v-if="enableUpdate" @click="handleEdit(scope.row)" type="text" icon="el-icon-edit">编辑</el-button>
          <el-button v-if="enableDelete" @click="handleDelete(scope.row)" type="text" icon="el-icon-delete" class="wl-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="wl-pagination" background
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100, 150, 200]"
      :page-size="pageSize"
      :total="count">
    </el-pagination>

    <!-- 弹出用户编辑框（SUPER） -->
    <el-dialog :title="dialogTitle" :visible.sync="dlgform.dialogFormVisible" v-loading.fullscreen.lock="loading" :close-on-click-modal="false" width="600px">
      <el-form ref="dlgform" :model="dlgform" :rules="rules" label-width="120px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="dlgform.userName" autocomplete="off" placeholder="输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="dlgform.userEmail" autocomplete="off" placeholder="输入邮箱地址"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPwd">
          <el-input type="password" v-model="dlgform.userPwd" autocomplete="off" placeholder="输入密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitDlgForm()" type="primary">确 定</el-button>
        <el-button @click="dlgform.dialogFormVisible=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 弹出用户编辑框（OWNER） -->
    <el-dialog title="编辑用户" :visible.sync="dlgmbform.dialogFormVisible" v-loading.fullscreen.lock="loading" :close-on-click-modal="false" width="600px">
      <el-form ref="dlgmbform" :model="dlgmbform" label-width="120px">
        <el-form-item label="成员角色" prop="role">
          <el-select v-model="dlgmbform.role" placeholder="请分配角色" class="wl-input">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitDlgMbForm()" type="primary">确 定</el-button>
        <el-button @click="dlgmbform.dialogFormVisible=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, addUser, updateUser, deleteUser } from '@/api/user'
import { getSpaceInfo, getSpaceMembers, editSpace, editSpaceMember, addSpaceMember, removeSpaceMember } from '@/api/space'

export default {
  name: 'User',
  data() {
    var checkEmail = (rule, value, callback) => {  // 邮箱验证规则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/
      return regEmail.test(value) ? callback() : callback(new Error('邮箱格式错误'))
    }
    var checkPwd = (rule, value, callback) => {    // 密码验证规则
      const regpwd = /^(\w){6,20}$/      // 6-20个字母、数字、下划线
      const regpwd2 = /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)[a-zA-Z\d]*$/  // 必须包含大写字母，小写字母，数字，特殊字符: /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)(?=.*?[#@*&.])[a-zA-Z\d#@*&.]*$/
      if (regpwd.test(value) && regpwd2.test(value)) {
        return callback()
      }
      return callback(new Error('至少6个字符，至少1个大写字母，1个小写字母和1个数字'))
    }
    return {
      loading: false,
      form: {
        queryName: ''
      },
      mbform: {
        userId: '',
        role: ''
      },
      dlgmbform: {  //编辑用户角色表单
        dialogFormVisible: false,
        userId: '',
        role: '',
        row: {}
      },
      enableCreate: false,
      memberList: [],  //空间用户列表
      count: 0,
      pageSize: 10,
      currentPage: 1,
      dlgform: {
        dialogFormVisible: false,
        editStatus: 1,  //编辑状态 1：新增 2：修改
        userId: '',
        userName: '',
        userPwd: '',
        userEmail: ''
      },
      rules: {
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        userPwd: [
          { required: true, message: '请设置密码', trigger: 'blur' },
          { validator: checkPwd, trigger: "blur" }
        ],
        userEmail: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: "blur" }
        ]
      },
      mbformRules: {
        userId: [{ required: true, message: '请选择用户名', trigger: 'blur' }],
        role: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      },
      space: {},
      userList: [],  // 添加成员下拉列表
      roleOptions: [
        { value: 'MASTER', label: '项目管理员' },
        { value: 'DEVELOPER', label: '开发者'},
        { value: 'REPORTER', label: '访客'}
      ]
    }
  },
  computed: {
    dialogTitle: function() {
      switch(this.dlgform.editStatus) {
        case 1: return '新增用户'
        case 2: return '编辑用户'
      }
    },
    enableShowCard: function() { // 只有空间所有者才有权限
      const space = this.$store.getters.space
      return (space.current && space.current.role === "OWNER")
    },
    enableUpdate: function() { // 判断是否有编辑权限
      return this.isSupper() || this.$store.getters.user.enable_update
    },
    enableDelete: function() { // 判断是否有删除权限
      return this.isSupper() || this.$store.getters.user.enable_delete
    }
  },
  created() {
    // init the default selected tab
  },
  mounted() {
    const space = this.$store.getters.space
    const user = this.$store.getters.user
    if (this.isSupper()) { // SUPER角色
      this.space = {}
      this.getUsers()
    } else if (space.current.id) { // 空间用户 // OWNER角色 space.current.role === "OWNER"
      this.loading = true
      getSpaceInfo(space.current.id).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
          return
        }
        let data = response.data.data
        if (data.status !== 1) {
          return
        }
        this.space = data
        this.getUsers()
      }).catch(error => {
        this.loading = false
        this.$message({ type:'error', message:'请求异常！'})
        console.log(error)
      })
    }
  },
  methods: {
    isSupper: function() { // 判断是超级用户
      const user = this.$store.getters.user
      return user.role === 'SUPER'
    }, 
    handleFocusUsers(event) { // 下拉添加成员
      this.getUserList(200)
    },
    handleInputUserName(e) {
      this.getUserList(200, 1, e.target.value.trim())
    },
    handleAddSpaceMember() { // 添加空间的成员
      this.$refs['mbform'].validate((valid) => {
        if (valid) {
          this.loading = true
          // let data = { ...this.space }
          // data.members.push({user_id:this.mbform.userId, role:this.mbform.role})
          // data.members = JSON.stringify(data.members)
          // editSpace(data.id, data).then(response => {
          //   this.loading = false
          //   if (!response.data || response.data.code !== 0) {
          //     this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
          //     return
          //   }
          //   this.mbform.userId = ''
          //   this.mbform.role = ''
          //   this.$message({ type:'success', message:'添加成功!' })
          //   this.getUsers()
          // }).catch(error => {
          //   this.loading = false
          //   this.$message({ type:'error', message:'请求异常！'})
          //   console.log(error)
          // })
          const space = this.$store.getters.space
          addSpaceMember(space.current.id, this.mbform.userId, this.mbform.role).then(response => {
            this.loading = false
            if (!response.data || response.data.code !== 0) {
              this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
              return
            }
            this.mbform.userId = ''
            this.mbform.role = ''
            this.$message({ type:'success', message:'添加成功!' })
            this.getUsers()
          }).catch(error => {
            this.loading = false
            this.$message({ type:'error', message:'请求异常！'})
            console.log(error)
          })
        }
      })
    },
    handleQuery(event) { // 查询
      this.getUsers()
    },
    handleAdd(event) { // 新增
      this.dlgform.dialogFormVisible = true
      this.dlgform.editStatus = 1
      this.dlgform.userId = '',
      this.dlgform.userName = '',
      this.dlgform.userEmail = '',
      this.dlgform.userPwd = '',
      this.resetDlgForm()
    },
    handleEdit(row) {  // 编辑
      const space = this.$store.getters.space
      const user = this.$store.getters.user
      if (space.current) { //OWNER角色
        this.dlgmbform.dialogFormVisible = true
        this.dlgmbform.userId = row.user_id
        this.dlgmbform.role = row.role
        this.dlgmbform.row = row
      } else if (this.isSupper()) { // SUPER角色
        this.dlgform.dialogFormVisible = true
        this.dlgform.editStatus = 2
        this.dlgform.userId = row.user_id
        this.dlgform.userName = row.username
        this.dlgform.userEmail = row.email
        this.dlgform.userPwd = ''
      }
    },
    handleDelete(row) { // 删除
      this.$confirm('确定删除该用户【' + row.username + '】吗?', '提示', {type:'warning', confirmButtonText:'确定', cancelButtonText:'取消'}).then(() => {
        if (this.isSupper()) {
          this.loading = true
          deleteUser(row.user_id).then(response => {
            this.loading = false
            if (!response.data || response.data.code !== 0) {
              this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
              return
            }
            this.getUsers()
            this.$message({ type: 'success', message: '删除成功！' })
          }).catch(error => {
            this.loading = false
            this.$message({ type: 'error', message: '删除失败!' });
          })
        } else {
          this.loading = true
          const space = this.$store.getters.space
          removeSpaceMember(space.current.id, row.user_id).then(response => {
            this.loading = false
            if (!response.data || response.data.code !== 0) {
              this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
              return
            }
            this.getUsers()
            this.$message({ type: 'success', message: '删除成功！' })
          }).catch(error => {
            this.loading = false
            this.$message({ type: 'error', message: '删除失败!' });
          })
        }
      })
    },
    handleSizeChange(pageSize) { // 设置分页大小事件
      this.pageSize = pageSize
      this.getUsers()
    },
    handleCurrentChange(pageno) { // 处理分页事件
      this.currentPage = pageno
      this.getUsers()
    },
    submitDlgMbForm() { // 提交修改用户角色表单
      this.loading = true
      const space = this.$store.getters.space
      const cdata = { ...this.dlgmbform.row }
      cdata.role = this.dlgmbform.role
      editSpaceMember(space.current.id, cdata).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
          return
        }
        this.getUsers()
        this.dlgmbform.dialogFormVisible = false
      }).catch(error => {
        this.loading = false
        this.$message({ type:'error', message:'请求异常！'})
        console.log(error)
      })
    },
    submitDlgForm() { // 提交新增空间用户表单
      this.$refs['dlgform'].validate((valid) => {
        if (valid) {
          switch(this.dlgform.editStatus) {
          case 1: // add
            this.loading = true
            addUser(this.dlgform.userName.trim(), this.dlgform.userEmail.trim(), this.dlgform.userPwd).then(response => {
              this.loading = false
              if (!response.data || response.data.code !== 0) {
                this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
                return
              }
              this.dlgform.dialogFormVisible = false
              this.loading = false
              this.getUsers()
            }).catch(error => {
              this.loading = false
              this.$message({ type:'error', message:'请求异常！'})
              console.log(error)
            })
            break
          case 2: // edit
            this.loading = true
            updateUser(this.dlgform.userId, this.dlgform.userName.trim(), this.dlgform.userEmail.trim(), this.dlgform.userPwd).then(response => {
              this.loading = false
              if (!response.data || response.data.code !== 0) {
                this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
                return
              }
              this.dlgform.dialogFormVisible = false
              this.getUsers()            
            }).catch(error => {
              this.loading = false
              this.$message({ type:'error', message:'请求异常！'})
              console.log(error)
            })
            break
          }
        } else {
          return false;
        }
      })
    },
    resetDlgForm() { // 重置新增用户表单
      if (this.$refs['dlgform'] !== undefined) { // 防止第一次DOM没有加载完
        this.$refs['dlgform'].resetFields()
      }
    },
    getUsers() { // 获取用户列表
      const space = this.$store.getters.space
      const user = this.$store.getters.user
      if (this.isSupper()) { // SUPER角色
        this.loading = true
        getUsers(this.pageSize, this.currentPage, this.form.queryName.trim()).then(response => {
          this.loading = false
          if (!response.data || response.data.code !== 0) {
            this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
            return
          }
          let data = response.data.data
          this.enableCreate = data.enable_create
          this.count = data.count
          this.memberList = data.list
          if (this.count > 0 && this.memberList.length==0) { // 调整PageNo
            this.currentPage = Math.ceil(this.count / this.pageSize)
            this.getUsers()
          }
        }).catch(error => {
          this.loading = false
          this.$message({ type:'error', message:'请求异常！'})
          console.log(error)
        })
      } else if (space.current.id) { // 空间的成员 && space.current.role === "OWNER" // OWNER角色 
        this.loading = true
        getSpaceMembers(space.current.id, this.pageSize, this.currentPage, this.form.queryName.trim()).then(response => {
          this.loading = false
          if (!response.data || response.data.code !== 0) {
            this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
            return
          }
          let data = response.data.data
          this.count = data.count
          this.memberList = data.list
          this.enableCreate = data.enable_create
        }).catch(error => {
          this.loading = false
          this.$message({ type:'error', message:'请求异常！'})
          console.log(error)
        })
      }
    },
    getUserList(size) {  // 获取可以添加到空间的用户
      this.loading = true
      getUsers(size).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
          return
        }
        let data = response.data.data
        this.userList = data.list
      }).catch(error => {
        this.loading = false
        this.$message({ type:'error', message:'请求异常！'})
        console.log(error)
      })
    },
    getRoleDesc(role) { // 角色描述
      switch(role) {
        case 'SUPER': return '超级用户'
        case 'OWNER': return '空间所有者'
        case 'MASTER': return '项目管理员'
        case 'DEVELOPER': return '开发者'
        case 'REPORTER': return '访客'
        default: return role
      }
    }
  }
}
</script>

<style scoped>
  .tab-container {
    margin: 20px;
  }
  .wl-card {
    margin-bottom: 20px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .wl-table {
    width:100%;
    margin-top: 10px;
  }
  .wl-input {
    width: 250px;
  }
  .wl-search {
    background:#f5f7fa;
  }
  .wl-append {
    margin-left: 15px;
  }
  .wl-delete {
    color: #f56c6c;
  }
  .wl-pagination {
    margin-top:10px;
  }
  .wl-avatar {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
  }
  .wl-avatar img {
    width: 30px;
    height: 30px;
    border-radius: 30px;
    display: block;
  }
</style>